package com.gly091020.ohMyPC;
// 来自 https://github.com/kikugie/crash-pipe 有修改

import net.neoforged.fml.loading.FMLPaths;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.gly091020.ohMyPC.OhMyPC.LOGGER;

public class SoundLoader {
    public static Path SOUND = FMLPaths.CONFIGDIR.get().resolve("oh_my_pc/oh_my_pc.wav");
    public static final List<Path> SOUNDS = new ArrayList<>();
    private static Clip clip;

    public static void init() {
        getSound().ifPresent(it -> {
            try {
                AudioInputStream is = AudioSystem.getAudioInputStream(it);
                clip = AudioSystem.getClip();
                clip.open(is);
            } catch (Exception e) {
                LOGGER.error("Couldn't load clip %s: %s".formatted(SOUND, e.getMessage()));
            }
        });
    }

    public static void tryPlay() {
        clip.setFramePosition(0);
        if (clip != null) {
            clip.start();
        }
    }

    private static Optional<File> getSound() {
        try {
            if (!Files.exists(SOUND)) {
                Files.createDirectories(SOUND.getParent());
                moveResource();
            }
            return Optional.of(SOUND.toFile().getAbsoluteFile());
        } catch (Exception e) {
            return Optional.empty();
        }
    }

    private static void moveResource() {
        for(int i = 0; i < 3; i++){
            String s;
            if(i == 0){
                s = "";
            }else{
                s = Objects.toString(i);
            }
            try (InputStream is = SoundLoader.class.getClassLoader()
                    .getResourceAsStream(String.format("assets/oh_my_pccccccccc/pc_sound/oh_my_pc%s.wav", s))) {
                if (is == null) throw new IllegalStateException("Sound resource not present");
                Files.copy(is, FMLPaths.CONFIGDIR.get().resolve(String.format("oh_my_pc/oh_my_pc%s.wav", s)));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    static {
        if (!Files.exists(SOUND)) {
            try {
                Files.createDirectories(SOUND.getParent());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            moveResource();
        }
        var l = FMLPaths.CONFIGDIR.get().resolve("oh_my_pc").toFile().listFiles();
        if(l != null) {
            for (File file : l) {
                SOUNDS.add(FMLPaths.CONFIGDIR.get().resolve("oh_my_pc").resolve(file.toPath()));
            }
        }
    }
}